# -*- encoding: utf-8 -*-
'''
Created on 2011-04-19

@author: quermit
'''
import json
import logging

import stompy
from PyQt4.QtCore import QThread
from PyQt4.QtCore import pyqtSignal


log = logging.getLogger(__name__)


class Reader(QThread):

    onMessage = pyqtSignal(object)

    def __init__(self, parent, host, port, topic_name, index_name):
        super(Reader, self).__init__(parent)
        self.__host = host
        self.__port = port
        self.__topic_name = topic_name
        self.__index_name = index_name

        self.__client = None
        self.__counter = 0
        self.__active = True

        self.finished.connect(self.__unsubscribe)

    def quit(self):
        self.__active = False
        super(Reader, self).quit()

    def run(self):
        try:
            client = self.__subscribe()
        except (stompy.stomp.ConnectionError, stompy.stomp.ConnectionTimeoutError), e:
            log.error("ConnectionError: %s" % e)
            return

        old_counter = self.__counter
        while self.__active:
            try:
                msg = client.get_nowait()
            except (stompy.simple.Empty, stompy.frame.UnknownBrokerResponseError):
                if self.__counter != old_counter:
                    log.debug("%s - new messages: %d" % (self.__topic_name, self.__counter - old_counter))
                    old_counter = self.__counter
                self.sleep(1)
            except stompy.simple.TransactionError, e:
                log.error("TransactionError: %s" % e)
                self.sleep(5)
            except stompy.stomp.NotConnectedError, e:
                log.error("NotConnectedError: %s" % e)
                return
            else:
                self.__handle_message(msg)

    def __subscribe(self):
        log.info("Connecting: %s:%d -> %s" %
                 (self.__host, self.__port, self.__topic_name))
        self.__client = stompy.simple.Client(host=self.__host, port=self.__port)
        self.__client.connect()
        self.__client.subscribe(self.__topic_name)
        log.info("Connected: %s:%d -> %s" %
                 (self.__host, self.__port, self.__topic_name))
        return self.__client

    def __unsubscribe(self):
        if self.__client:
            self.__client.unsubscribe(self.__topic_name)
            self.__client.disconnect()
            self.__client = None
            log.info("Disconnected: %s:%d -> %s" %
                     (self.__host, self.__port, self.__topic_name))

    def __handle_message(self, msg):
        if not msg:
            return
        try:
            body = json.loads(msg.body)
        except ValueError, e:
            log.warning("Message parse error: %s" % e)
        else:
            self.__counter += 1
            body['origin_index'] = self.__index_name
            self.onMessage.emit(body)
